<script setup>
import { ref } from 'vue'
import moment from 'moment';
import { 
  expensePageService,
  updateExpenseStatusService,
  deleteExpenseService 
} from "@/api/expense";
import { ElMessage, ElMessageBox } from "element-plus";

// 搜索条件
const searchForm = ref({
  userName: '',
  expenseType: '',
  departmentName: '',
  status: '',
})

// 分页数据
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数
 //当每页条数发生了变化，调用此函数
 const onSizeChange = (size) => {
  pageSize.value = size
  employeeList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  page.value = num
  employeeList()
}
// 报销数据
const expenseData = ref([])

// 部门选项
const departmentOptions = ref([])

// 报销类型选项
const expenseTypeOptions = [
  { label: '交通费', value: 0 },
  { label: '差旅费', value: 1 },
  { label: '办公用品', value: 2 },
  { label: '业务招待', value: 3 }
]

// 状态选项
const statusOptions = [
  { label: '待审核', value: 0 },
  { label: '已通过', value: 1 },
  { label: '已拒绝', value: 2 },
  { label: '已撤销', value: 3 }
]

// 获取报销列表
const getExpenseList = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    ...searchForm.value
  }
  const result = await expensePageService(params)
  if (result.code === 0 && result.data) {
        total.value = result.data.records.length; // 这里直接使用返回数组的长度作为总记录数，如果后端有专门的total字段，需调整为对应取值
        expenseData.value = result.data.records.map(item => ({
           ...item,
            statusLabel: statusOptions.find(s => s.value === item.status)?.label,
            typeLabel: expenseTypeOptions.find(t => t.value === item.expenseType)?.label
        }));
    } else {
        console.error('获取报销列表失败:', result.message);
    }
}

// 处理审核
const handleApprove = async (row, status) => {
  try {
    const { value: remark } = await ElMessageBox.prompt(
      `请输入${status === 1 ? '通过' : '拒绝'}原因`,
      '审核备注',
      {
        inputPlaceholder: '请输入审核意见',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    )
    
    const params = {
      id: row.id,
      status,
      remark
    }
    
    await updateExpenseStatusService(params)
    ElMessage.success(status === 1 ? '审核通过' : '审核拒绝')
    getExpenseList()
  } catch (e) {
    // 取消操作不处理
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该报销记录？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteExpenseService(row.id)
    ElMessage.success('删除成功')
    getExpenseList()
  })
}

// 初始化加载
 getExpenseList()
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>报销管理</span>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline>
     

      <el-form-item label="申请人">
        <el-input 
          v-model="searchForm.userName" 
          placeholder="请输入申请人"
          style="width: 150px"
        />
      </el-form-item>


      <el-form-item label="类型">
        <el-select
          v-model="searchForm.expenseType"
          clearable
          placeholder
          style="width: 120px"
        >
          <el-option
            v-for="item in expenseTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select
          v-model="searchForm.status"
          clearable
          placeholder="全部状态"
          style="width: 120px"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getExpenseList">搜索</el-button>
        <el-button @click="searchForm = {}">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="expenseData" stripe>
      <el-table-column prop="departmentName" label="部门" width="120"/>
      <el-table-column prop="userName" label="申请人" width="100"/>
      <el-table-column prop="subject" label="报销主题" width="150"/>
      <el-table-column prop="typeLabel" label="类型" width="100"/>
      <el-table-column prop="amount" label="金额" width="120">
        <template #default="{row}">￥{{ row.amount }}</template>
      </el-table-column>
      <el-table-column prop="statusLabel" label="状态" width="120">
        <template #default="{row}">
          <el-tag 
            :type="row.status === 1 ? 'success' : row.status === 2 ? 'danger' : 'warning'"
            effect="plain"
          >
            {{ row.statusLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请材料" prop="applyDocuments">
      <template #default="{ row }">
        <el-image 
          style="width: 100px; height: 100px; border-radius: 4px"
          :preview-teleported="true"
          :src="row.applyDocuments"
          :preview-src-list="[row.applyDocuments]"
          :initial-index="4"
          fit="cover"
        >
          <template #error>
            <div class="image-error-placeholder">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
      </template>
    </el-table-column>
      <el-table-column prop="submitTime" label="提交时间" width="180"/>
      
      <el-table-column label="操作" width="210" fixed="right">
        <template #default="{row}">
          <el-button 
            v-if="row.status === 0"
            type="success" 
            size="small"
            @click="handleApprove(row, 1)"
          >
            通过
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="danger"
            size="small"
            @click="handleApprove(row, 2)"
          >
            拒绝
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <!-- 分页条 -->
    <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-tag {
  margin: 2px;
}
</style>